using System;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;

public class UserManager : MonoBehaviour
{
    public static UserManager Instance { get; private set; }
    private const string UserInfoKey = "User_Info_CrazyFood";
    void Awake()
    {
#if UNITY_EDITOR
        // 在编辑器环境中清除所有的 PlayerPrefs 数据
        PlayerPrefs.DeleteAll();
        Debug.Log("已在编辑器环境中清除所有 PlayerPrefs 数据");
#endif
        if (Instance == null)
        {
            Instance = this;
            //初始化用户数据
            InitUserData();
        }
        else
        {
            Destroy(gameObject);
        }
    }

    public void InitUserData()
    {
        JObject userData = GetUserInfo();

        if (userData == null)
        {
            Debug.Log("没有用户数据初始化用户数据");
            JObject defaultUserData = new JObject
            {
                ["CurrentLv"] = 1,
                ["Coins"] = 0,
                ["Uid"] = Tools.GenerateRandomUid(),
                ["ActiveTime"] = DateTime.Now,
                ["Tesla"] = 0,
                ["LimitedLv"] = 1,
                ["IsEmergencyic"] = false,
            };
            SetUserInfo(defaultUserData);
        }
        else
        {
            Debug.Log("有用户数据");
        }
    }

    public JObject GetUserInfo()
    {
        string data = PlayerPrefs.GetString(UserInfoKey, string.Empty);
        Debug.Log("获取用户信息数据" + data);
        if (string.IsNullOrEmpty(data)) return null;

        return JsonConvert.DeserializeObject<JObject>(data); // 指定反序列化成 JObject
    }

    public static void SetUserInfo(JObject userInfo)
    {
        string serializedData = JsonConvert.SerializeObject(userInfo);
        Debug.Log("设置用户信息数据" + serializedData);
        PlayerPrefs.SetString(UserInfoKey, serializedData);
        PlayerPrefs.Save();
    }

    public void AddCoins(float amount)
    {
        JObject userData = GetUserInfo();

        if (userData != null)
        {
            float currentCoins = userData.Value<float>("Coins");
            float newCoins = Mathf.Round((currentCoins + amount) * 100f) / 100f;
            userData["Coins"] = newCoins;
            SetUserInfo(userData);
            GlobalEventManager.EmitEvent<float>("UpdateCoins", newCoins);
        }
        else
        {
            Debug.LogError("无法获取用户数据，无法添加金币");
        }
    }

    public void SubtractCoins(float amount)
    {
        JObject userData = GetUserInfo();

        if (userData != null)
        {
            float currentCoins = userData.Value<float>("Coins");
            if (currentCoins >= amount)
            {
                float newCoins = Mathf.Round((currentCoins - amount) * 100f) / 100f;
                userData["Coins"] = newCoins;
                SetUserInfo(userData);
                GlobalEventManager.EmitEvent<float>("UpdateCoins", newCoins);
                Debug.Log($"金币已减少，新金币数: {newCoins}");
            }
            else
            {
                Debug.LogWarning("金币不足，无法扣除该数量的金币");
            }
        }
        else
        {
            Debug.LogError("无法获取用户数据，无法减少金币");
        }
    }

    public void AddTesla(float tesla)
    {
        JObject userData = GetUserInfo();

        if (userData != null)
        {
            float currentTesla = userData.Value<float>("Tesla");
            float newTesla = Mathf.Round((currentTesla + tesla) * 100f) / 100f;
            userData["Tesla"] = newTesla;
            SetUserInfo(userData);
            GlobalEventManager.EmitEvent<float>("UpdateTesla", newTesla);
        }
        else
        {
            Debug.LogError("无法获取用户数据，无法添加tesla");
        }
    }

    public void SubtractTesla(float tesla)
    {
        JObject userData = GetUserInfo();

        if (userData != null)
        {
            float currentTesla = userData.Value<float>("Tesla");
            if (currentTesla >= tesla)
            {
                float newTesla = Mathf.Round((currentTesla - tesla) * 100f) / 100f;
                userData["Tesla"] = newTesla;
                SetUserInfo(userData);
                GlobalEventManager.EmitEvent<float>("UpdateTesla", newTesla);
                Debug.Log($"tesla已减少，tesla数: {newTesla}");
            }
            else
            {
                Debug.LogWarning("tesla不足，无法扣除该数量的tesla");
            }
        }
        else
        {
            Debug.LogError("无法获取用户数据，无法减少tesla");
        }
    }

    //升级
    public void LevelUp()
    {
        JObject userData = GetUserInfo();

        if (userData != null)
        {
            int currentLv = userData.Value<int>("CurrentLv");
            int newLv = currentLv + 1;
            userData["CurrentLv"] = newLv;
            SetUserInfo(userData);
        }
    }

    //升级LimitedLv
    public void LevelUpLimitedLv()
    {
        JObject userData = GetUserInfo();

        if (userData != null)
        {
            int currentLv = userData.Value<int>("LimitedLv");
            int newLv = currentLv + 1;
            userData["LimitedLv"] = newLv;
            SetUserInfo(userData);
        }
    }

    //设置IsEmergencyic
    public void SetIsEmergencyic(bool isEmergencyic)
    {
        JObject userData = GetUserInfo();

        if (userData != null)
        {
            userData["IsEmergencyic"] = isEmergencyic;
            SetUserInfo(userData);
        }
    }
}
